<?php


namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Utils\VideoUtil;
use App\Services\QiniuService;
use Qiniu\Storage\UploadManager;
use App\Utils\Code;
use App\Utils\Tools;
use Fukuball\Jieba\Jieba;
use Fukuball\Jieba\Finalseg;

class TestController extends Controller
{
    /**
     * @api {post} videocut 剪切视频
     */
    public function videocut(Request $request) {
        $videoUrl = $request->input('videoUrl');
        $videoSS = $request->input('videoSS');
        $videoT = (double)$request->input('videoT');
        $rate = (double)$request->input('rate');
        $footageId = $request->input('footageId');
        $partId = $request->input('partId');

        $originVideoDirPath = public_path('storage').'/originVideo';
        $midVideoDirPath = public_path('storage').'/'.$footageId.'/midVideo';
        if (!is_dir($midVideoDirPath)) {
            mkdir($midVideoDirPath, 0777, true);
        }
        VideoUtil::download_video(
            config('app.qiniu_url').'/'.$videoUrl,
            $originVideoDirPath,
            $videoUrl
        );
        $inputPath = $originVideoDirPath.'/'.$videoUrl;
        $outputPath = $midVideoDirPath.'/output'.$partId.'.mp4';
        $duration = $videoT * $rate;
        $setpts = 1 / $rate;
        $command = "ffmpeg -ss {$videoSS} -t {$duration} -i {$inputPath} -filter:v setpts={$setpts}*PTS -an {$outputPath}";
        // 执行命令
        exec($command, $output, $return_var);
        // 上传七牛云
        $token = (new QiniuService())->getToken([]);
        $uploadMgr = new UploadManager();
        $data = $uploadMgr->putFile($token, null, $outputPath);
        rename($outputPath, $midVideoDirPath.'/'.$data[0]['key']);
        return $data[0]['key'];
    }

    /**
     * @api {post} videogen 视频生成
     */
    public function videogen(Request $request) {
        $audioUrl = $request->input('audioUrl');
        $footageId = $request->input('footageId');
        $parts = $request->input('parts');
    
        $workDirPath = public_path('storage').'/'.$footageId;
        $midVideoDirPath = public_path('storage').'/'.$footageId.'/midVideo';
        $audioName = 'audio.mp3';
        VideoUtil::download_video(
            config('app.qiniu_url').'/'.$audioUrl, 
            $workDirPath,
            $audioName
        );
        $inputTxtPath = $workDirPath.'/'.'input.txt';
        $file = fopen($inputTxtPath, 'w');
        foreach($parts as $part) {
            $partPath = !empty($part['path']) ? $part['path'] : '';
            if ($partPath) {
                VideoUtil::download_video(
                    config('app.qiniu_url').'/'.$partPath,
                    $midVideoDirPath,
                    $partPath
                );
                fwrite($file, 'file midVideo/'.$partPath . PHP_EOL);
            }
        }
        fclose($file);
        $audioPath = $workDirPath.'/'.$audioName;
        $outputName = 'product'.date('YmdHis').'.mp4';
        $outputPath = $workDirPath.'/'.$outputName;
        // $command = "ffmpeg -f concat -safe 0 -i {$inputTxtPath} -c:v libx264 {$outputPath}";
        // $command = "ffmpeg -f concat -safe 0 -i {$inputTxtPath} -i {$audioPath} -c copy -map 0:v -map 1:a {$outputPath}";
        $command = "ffmpeg -f concat -safe 0 -i {$inputTxtPath} -i {$audioPath} -c:v libx264 -c:a aac -strict experimental -map 0:v -map 1:a -r 30 -shortest {$outputPath}";
        exec($command, $output, $return_var);
        if ($return_var !== 0) {
            return "合并视频处理失败";
        }
        $token = (new QiniuService())->getToken([]);
        $uploadMgr = new UploadManager();
        $data = $uploadMgr->putFile($token, $outputName, $outputPath);
        rename($outputPath, $workDirPath.'/'.$data[0]['key']);
        return $data[0]['key'];
    }
    
    /**
     * @api {post} videocut 剪切视频
     */
    public function videoToAudio(Request $request) {
        if (!$file = $request->file('file')) {
            throw new \Exception('没有上传任何文件', Code::PARAMETER_ERROR);
        }
        $name = $request->input('name');
        $inputPath = $file->store('public');
        // return $inputPath;
        // rename($inputPath, public_path('storage').'/'.);
        // $inputPath = storage_path('app/public').'/'.$fileName;
        $inputPath = storage_path('app').'/'.$inputPath;
        $outputPath = storage_path('app/public').'/'.date('YmdHis').'.mp3';
        $command = "ffmpeg -i {$inputPath} {$outputPath}";
        // 执行命令
        exec($command, $output, $return_var);
        // 上传七牛云
        $token = (new QiniuService())->getToken([]);
        $uploadMgr = new UploadManager();
        $data = $uploadMgr->putFile($token, null, $outputPath);
        return $data[0]['key'];
    }
    
    /**
     * @api {post} videocut 剪切视频
     */
    public function audiocut(Request $request) {
        $audioUrl = $request->input('audioUrl');
        $audioSS = $request->input('audioSS');
        $audioT = (double)$request->input('audioT');

        $originAudioDirPath = public_path('storage').'/originAudio';
        $midAudioDirPath = public_path('storage').'/midAudio';
        if (!is_dir($originAudioDirPath)) {
            mkdir($originAudioDirPath, 0777, true);
        }
        if (!is_dir($midAudioDirPath)) {
            mkdir($midAudioDirPath, 0777, true);
        }
        VideoUtil::download_video(
            config('app.qiniu_url').'/'.$audioUrl,
            $originAudioDirPath,
            $audioUrl
        );
        $inputPath = $originAudioDirPath.'/'.$audioUrl;
        $outputPath = $midAudioDirPath.'/'.date('YmdHis').'.mp3';
        $duration = $audioT;
        $command = "ffmpeg -i {$inputPath} -ss {$audioSS} -t {$duration} -acodec copy {$outputPath}";
        // 执行命令
        exec($command, $output, $return_var);
        // 上传七牛云
        $token = (new QiniuService())->getToken([]);
        $uploadMgr = new UploadManager();
        $data = $uploadMgr->putFile($token, null, $outputPath);
        rename($outputPath, $midAudioDirPath.'/'.$data[0]['key']);
        return $data[0]['key'];
    }

    public function test() {
        ini_set('memory_limit', '512M');
        try {
            Jieba::init();
            Finalseg::init();
            $string = '你要问些什么问题呢';
            $word = Tools::break_string($string, 1, 'array'); // 分成单个字
            $aword = Jieba::cut($string);
            $case = '';
            foreach ($word as $k => $wd) {
                // 全部被打散的单个字 
                if ($wd == '.' || $wd == ' ' || $wd == '。' || $wd == '，' || $wd == '；' || $wd == ',' || $wd == '?' || $wd == '？' || $wd == '：' || $wd == ':' || $wd == '+' || $wd == '-' || $wd == '/' || $wd == '\\') { } else {
                    $case .= "CASE WHEN field_1 LIKE '%$wd%' THEN 1 ELSE 0 END + ";
                }
            }
            foreach ($aword as $k => $wd) {
                // 分词 
                $case .= "CASE WHEN field_1 LIKE '%$wd%' THEN 2 ELSE 0 END + ";
            }
            $case .= " 0 as search ,";
            // 使用phpanalysis进行分词
            return $case;
            return [$word, $aword];
        } catch (\Exception $e) {
            echo $e->getMessage();
            // return $e;
            // Code::log($e->getMessage());
        }
    }
}
